#!/usr/bin/env node
/**
 * ChainValidator CLI
 * 用法：npm run chainvalidator -- ComponentName
 */
const fs = require('fs');
const path = require('path');
const ts = require('typescript');

function loadChainValidator() {
  const filePath = path.join(__dirname, '../.claude/agents/ChainValidator/chain-validator.ts');
  const source = fs.readFileSync(filePath, 'utf8');
  const compiled = ts.transpileModule(source, {
    compilerOptions: { module: ts.ModuleKind.CommonJS, esModuleInterop: true },
    fileName: filePath,
  });
  const moduleWrapper = { exports: {} };
  const func = new Function(
    'require',
    'module',
    'exports',
    '__dirname',
    '__filename',
    compiled.outputText,
  );
  func(require, moduleWrapper, moduleWrapper.exports, path.dirname(filePath), filePath);
  return moduleWrapper.exports;
}

const { ChainValidator } = loadChainValidator();

async function main() {
  const componentName = process.argv[2];
  if (!componentName) {
    console.error('❌ 缺少组件名称');
    console.error('用法：npm run chainvalidator -- ComponentName');
    process.exit(1);
  }

  const root = process.cwd();
  const outputDir = path.join(root, componentName, 'phase5');
  const outputFile = path.join(outputDir, `${componentName}-validation-results.json`);

  const fieldsFile = path.join(root, 'src/components/editor/schema/fields/aiComponents.ts');
  const editFile = path.join(root, 'src/components/editor/schema/edit/aiComponents.ts');
  const previewFile = path.join(
    root,
    'src/components/editor/schema/preview/components',
    componentName,
    'index.tsx',
  );
  const rightRoot = path.join(root, 'src/components/editor/Right');

  console.log('\n[ChainValidator] 当前组件:', componentName);
  console.log('  fieldsFile :', fieldsFile, fs.existsSync(fieldsFile) ? '✅' : '❌');
  console.log('  editFile   :', editFile, fs.existsSync(editFile) ? '✅' : '❌');
  console.log('  previewFile:', previewFile, fs.existsSync(previewFile) ? '✅' : '❌');
  console.log('  rightRoot  :', rightRoot, fs.existsSync(rightRoot) ? '✅' : '❌');

  const validator = new ChainValidator();
  const result = await validator.validateChain(componentName, {
    fieldsFile,
    editFile,
    previewFile,
    rightRoot,
  });

  console.log('\nChainValidator 校验结果：');
  console.log(`  状态：${result.status}`);
  console.log(`  得分：${result.score}`);
  console.log(`  连通性：${result.connectivity}`);
  console.log(
    `  覆盖率 - Fields: ${result.fields_coverage}, Edit: ${result.edit_coverage}, Preview: ${result.preview_coverage}, EditMapping: ${result.edit_mapping_coverage}`,
  );

  if (result.errors.length) {
    console.log('\n错误：');
    result.errors.forEach((err) =>
      console.log(`  - [${err.layer}] ${err.field}: ${err.message}`),
    );
  }

  if (result.warnings.length) {
    console.log('\n警告：');
    result.warnings.forEach((warn) =>
      console.log(`  - [${warn.layer}] ${warn.field}: ${warn.message}`),
    );
  }

  if (!fs.existsSync(outputDir)) {
    fs.mkdirSync(outputDir, { recursive: true });
  }

  let report = {};
  if (fs.existsSync(outputFile)) {
    try {
      report = JSON.parse(fs.readFileSync(outputFile, 'utf8'));
    } catch {
      report = {};
    }
  }

  report.component = componentName;
  report.timestamp = new Date().toISOString();
  report.results = report.results || {};
  report.results.chainValidator = result;

  fs.writeFileSync(outputFile, JSON.stringify(report, null, 2));
  console.log(`\n已写入 ${outputFile}`);

  if (!result.valid) {
    process.exit(1);
  }
}

main().catch((error) => {
  console.error(`ChainValidator 执行失败：${error.message}`);
  process.exit(1);
});
